package com.pai4j.zwiki.messagequeue.consumer.service;

import com.pai4j.zwiki.dto.ZWikiNotificationMessage;
import com.pai4j.zwiki.enums.ZWikiNotificationType;
import com.pai4j.zwiki.websocket.service.ZWikiWebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * ZWiki通知消费服务
 * 处理Redis发布的通知消息，通过WebSocket实时推送给用户
 *
 * @author pai4j
 * @since 2025-10-14
 * @updated 2025-10-14 集成WebSocket实时推送
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ZWikiNotificationConsumeService {

    private final ZWikiWebSocketService webSocketService;

    /**
     * 处理任务通知（入队、开始、完成、失败）
     */
    public void handleTaskNotification(ZWikiNotificationMessage notification) {
        log.info("处理任务通知: type={}, taskId={}, userId={}", 
                notification.getNotificationType(), 
                notification.getTaskId(), 
                notification.getUserId());

        try {
            // 根据通知类型进行不同处理
            ZWikiNotificationType notificationType = 
                    ZWikiNotificationType.valueOf(notification.getNotificationType());

            switch (notificationType) {
                case TASK_QUEUED:
                    handleTaskQueuedNotification(notification);
                    break;
                case TASK_STARTED:
                    handleTaskStartedNotification(notification);
                    break;
                case TASK_COMPLETED:
                    handleTaskCompletedNotification(notification);
                    break;
                case TASK_FAILED:
                    handleTaskFailedNotification(notification);
                    break;
                default:
                    log.warn("未知的通知类型: {}", notification.getNotificationType());
            }

        } catch (Exception e) {
            log.error("处理任务通知失败: {}", notification.getTaskId(), e);
        }
    }

    /**
     * 处理进度通知
     */
    public void handleProgressNotification(ZWikiNotificationMessage notification) {
        log.debug("处理进度通知: taskId={}, progress={}%", 
                notification.getTaskId(), notification.getProgress());

        try {
            // 推送到WebSocket
            webSocketService.pushTaskProgressUpdate(
                    notification.getUserId(),
                    notification.getTaskId(),
                    notification.getProgress(),
                    notification.getCurrentStep()
            );
            
            log.debug("进度通知已处理并推送: taskId={}, progress={}%", 
                    notification.getTaskId(), notification.getProgress());

        } catch (Exception e) {
            log.error("处理进度通知失败: {}", notification.getTaskId(), e);
        }
    }

    /**
     * 处理队列更新通知
     */
    public void handleQueueUpdateNotification(ZWikiNotificationMessage notification) {
        log.debug("处理队列更新通知: taskId={}, queuePosition={}", 
                notification.getTaskId(), notification.getQueuePosition());

        try {
            // 推送到WebSocket
            webSocketService.pushQueuePositionUpdate(
                    notification.getUserId(),
                    notification.getTaskId(),
                    notification.getQueuePosition()
            );
            
            log.debug("队列更新通知已处理并推送: taskId={}, position={}", 
                    notification.getTaskId(), notification.getQueuePosition());

        } catch (Exception e) {
            log.error("处理队列更新通知失败: {}", notification.getTaskId(), e);
        }
    }

    // ========== 私有方法 ==========

    private void handleTaskQueuedNotification(ZWikiNotificationMessage notification) {
        log.info("任务已入队: taskId={}, queuePosition={}, estimatedWait={}min", 
                notification.getTaskId(), 
                notification.getQueuePosition(),
                notification.getEstimatedWaitTime());
        
        // 推送到WebSocket
        webSocketService.pushTaskQueuedNotification(
                notification.getUserId(),
                notification.getTaskId(),
                notification.getQueuePosition(),
                notification.getEstimatedWaitTime()
        );
    }

    private void handleTaskStartedNotification(ZWikiNotificationMessage notification) {
        log.info("任务已开始: taskId={}, projectName={}", 
                notification.getTaskId(), 
                notification.getProjectName());
        
        // 推送到WebSocket
        webSocketService.pushTaskStartedNotification(
                notification.getUserId(),
                notification.getTaskId(),
                notification.getProjectName()
        );
    }

    private void handleTaskCompletedNotification(ZWikiNotificationMessage notification) {
        log.info("任务已完成: taskId={}, projectName={}", 
                notification.getTaskId(), 
                notification.getProjectName());
        
        // 推送到WebSocket
        webSocketService.pushTaskCompletedNotification(
                notification.getUserId(),
                notification.getTaskId(),
                notification.getProjectName(),
                notification.getMessage()
        );
        
        // TODO: 可以在这里添加邮件通知
        // emailService.sendTaskCompletedEmail(notification);
    }

    private void handleTaskFailedNotification(ZWikiNotificationMessage notification) {
        log.warn("任务失败: taskId={}, error={}", 
                notification.getTaskId(), 
                notification.getErrorMessage());
        
        // 推送到WebSocket
        webSocketService.pushTaskFailedNotification(
                notification.getUserId(),
                notification.getTaskId(),
                notification.getErrorMessage()
        );
        
        // TODO: 可以在这里添加告警通知
        // alertService.sendTaskFailedAlert(notification);
    }
}

